package vip.ola.pay.channel.dragonpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.DateUtil;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.BasePayment;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static vip.ola.core.common.constant.Constant.UTF8;
import static vip.ola.core.common.constant.PayEnum.ERR_0010;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

@Service
public class SlcloudPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(SlcloudPaymentService.class);

    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String getChannelName() {
        return null;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        try {
            System.out.println("话费支付使用子账号ID：" + payOrder.getChannelMchId());
            PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String productId="8003";
            String subject = "移动话费充值";
            String orderId = payOrder.getPayOrderId();
            String clientIp = "211.99.100.200";
            String prePayUrl = accountParams.getString("payUrl");
            String payUrl = "";
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("mchId", mchId);  //商户ID
            params.put("appId", "3a5051de4a9b405caf07ecfbc6332956");  //商户应用ID
            params.put("productId", productId);  //支付产品ID
            params.put("mchOrderNo", orderId);   //商户订单号
            params.put("currency", "cny");   //币种
            params.put("amount", payOrder.getAmount());   //支付金额
            params.put("clientIp", clientIp);   //客户端IP
            params.put("notifyUrl", accountParams.getString("notify_url"));   //支付结果后台回调URL
            params.put("subject", subject);  //商品主题
            params.put("body", "网络购物");   //商品描述信息
            params.put("reqTime", DateUtil.date2Str(new Date(), DateUtil.FORMAT_YYMMDDHHMMSS));  //请求时间, 格式yyyyMMddHHmmss
            params.put("version", "1.0");  //版本号, 固定参数1.0

            String sign = PayDigestUtil.getSign(params, payPassageAccount.getPrivateKey());  //签名
            params.put("sign", sign);
            String respData = call(prePayUrl,params);
            _log.info("下单返回={}",respData);
            JSONObject resObj = JSON.parseObject(respData);
            if ("0".equals(resObj.getString("retCode")))
            {
                String channelOrderNO = resObj.getString("payOrderId");
                int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), channelOrderNO);
                payUrl = resObj.getString("payUrl");
                return PayUtil.makeRetPayUrl(payUrl,null);
            }
            return PayUtil.makeRetFail(ERR_0010);
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return PayUtil.makeRetFail(ERR_0010);
        }
    }

    public static String call(String url, Map param) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        // 响应模型
        CloseableHttpResponse response = null;
        String responseContext = null;
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseContext = EntityUtils.toString(responseEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContext;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        return null;
    }
}

